package net.xdclass.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author guangyang
 * @since 2023-01-16
 **/

@Api("验证码生成")
@RestController
@RequestMapping("/api/user/v1")
@Slf4j
public class NotifyController  {
    @Autowired
    private Producer producer;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private NotifyService notifyService;

    /**
    * 图形验证码有效期10分钟
    */
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;


    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String producerText = producer.createText();
        log.info("生成验证码{}",producerText);
//        存入redis后，生成图片验证码
        redisTemplate.opsForValue().set(getCaptchaKey(request),producerText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        BufferedImage image = producer.createImage(producerText);
        try {
            ServletOutputStream outputStream=response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            //清空缓存区//关闭流
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.error("获取图形验证码异常{}",e.getMessage(),e);
        }


    }

    /**
     * 发送验证码
     * @param to 收件人
     * @param captcha 验证码
     * @return JsonData封装类
     */
    @ApiOperation("发送邮箱注册验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@RequestParam(value = "to",required = true) String to,
                                     @RequestParam(value = "captcha",required = true) String captcha,
                                     HttpServletRequest request){

        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);

        //匹配图形验证码是否一样
        if(captcha !=null && to !=null && captcha.equalsIgnoreCase(cacheCaptcha)){
            //成功
            redisTemplate.delete(key);
            return notifyService.sendCode(SendCodeEnum.USER_REGISTER,to);

        }else{
            return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);
        }

    }

    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String header = request.getHeader("User-Agent");
        String key= String.format(CacheKey.CAPTCHA_CODE_KEY,CommonUtil.MD5(ip+header) );

        log.info("ip={}",ip);
        log.info("userAgent={}",header);
        log.info("key={}",key);
        return key;

    }

}
